package priv.bruce.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;

import priv.bruce.entry.UserInfo;
import priv.bruce.util.JDBCUtil;

public class AddCommentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();

//		session.setAttribute("user_name", "aab");
//		session.setAttribute("user_id", "3");

		if (session.getAttribute("user_name") != null) {
			UserInfo userInfo = new UserInfo();
			userInfo.setUser_name(session.getAttribute("user_name").toString());
			userInfo.setUser_id(Long.parseLong(session.getAttribute("user_id").toString()));
			response.getWriter().append(JSON.toJSONString(userInfo));
		} else {
			response.getWriter().append(JSON.toJSONString(null));
		}
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setContentType("application/json;charset=utf-8");
		int uid=Integer.parseInt(request.getParameter("user_id"));
		String conetnt=request.getParameter("comment_content");
		int score=Integer.parseInt(request.getParameter("score"));
		int mid=Integer.parseInt(request.getParameter("movie_id"));
		
		SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long time=Long.parseLong(request.getParameter("comment_time"));
		String d = format.format(time);
		Date date;
			try {
				String sql1="INSERT INTO t_comment(user_id,movie_id,comment_content,"
						+ "comment_time)VALUES(?,?,?,?)";
				date = format.parse(d);
				JDBCUtil.update(sql1,uid,mid,conetnt,date);
			} catch (ParseException e1) {
				e1.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			String sql2="INSERT INTO t_score(user_id,movie_id,score)values(?,?,?)";
			try {
				if (score==0) {
					return;
				}
				else {
					JDBCUtil.update(sql2,uid,mid,score);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
	}
}
